package com.example.wxCode.utils.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.wxCode.utils.http.ApacheHttpUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import static com.example.wxCode.utils.http.ApacheHttpUtil.sendGet;
import static com.example.wxCode.utils.wx.constants.WXQRUrl.WX_ACCESS_TOKEN;

/**
 * @Description 获取接口凭证 accesstoken
 * @Author zengzerui
 * @Date 2025/4/15
 */
@Slf4j
@Component
@Data
public class AccessTokenUtil {

    @Value("${wx.conf.appId:123}")
    public String APP_ID;
    @Value("${wx.conf.appSecret}")
    public String SECRET;

    public String getAccessToken() {
        String accessToken = null;
        String url = WX_ACCESS_TOKEN + "&appid=" + APP_ID + "&secret=" + SECRET;
        log.info("请求地址:" + url);
        String response = ApacheHttpUtil.sendGet(url.trim(), null);
        JSONObject json = JSON.parseObject(response);
        //如果不存在errocode就是请求正常的
        if (!json.containsKey("errcode")) {
            accessToken = json.getString("access_token");
            if (StringUtils.isEmpty(accessToken)) {
                log.error("获取AccessToken异常,{}", json);
                return "";
            }
            return accessToken;
        } else {
        }
        return accessToken;
    }

}
